package com.meevle.view.components.visualization
{

	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Graphics;
	import flash.events.Event;
	import flash.filters.BitmapFilterQuality;
	import flash.filters.BlurFilter;
	import flash.media.SoundMixer;
	import flash.utils.ByteArray;
	
	public class FrequencyVisualization extends BaseVisualization
	{
		public var lColor:uint = 0x00FF00;
		public var rColor:uint = 0xFF0000;
		
		private var current : Number = 0;
		protected var wInterval : Number = 0;
		protected var vInterval : Number = 0;
		public var bars : Number = 25;
		private var span : Number = 1;
		
		override protected function updateDisplayList(w:Number, h:Number):void {
			super.updateDisplayList(w, h);

			span = w/bars;
			vInterval = Math.floor( h/2 );
		}
		
		override protected function drawVisualization( e : Event ) : void
		{
			if( !this.visible ) return;      
			
			/* 
			FFTMode doesn't seem to work correctly
			it doesn't return a true spectrum analyis 
			and it also does not seem to return values correctly.
			The docs state that it should return a value between -1 and 1.
			I've traced the output and definitely seen values > 1
			
			But it still looks cool
			*/
			
			SoundMixer.computeSpectrum(spectrum, true);
			
			var g : Graphics = this.graphics;
			var i:uint
			var x:uint;
			var z:uint = 0;
			var vOffset : Number;
			
			g.clear();
			g.endFill();
			g.lineStyle( ((bars <= 30) ? 1 : 0), 0xFFFFFF, ((bars <= 30) ? 1 : 0));
			
			//g.drawRect(0,0,width,height);
			g.beginFill( lColor, 1 );
			//left channel
			for (i = 0; i < bars ; i++) 
			{
				current = 0;
				for (x = 0; x < Math.floor(256/bars) ; x++) {
                    current = Math.max(current, spectrum.readFloat());
                    z++;
				}
				current = Math.min( current, 1 );
				
				vOffset = (vInterval * current);
				g.drawRect( (i*span), (vInterval - vOffset), span, vOffset );

			}
			g.endFill();
			
			while (z < 256)
			{
				current = spectrum.readFloat();
				z++;
			}
			z=0;
			           	
			g.beginFill( rColor, 1 );
			//right channel
			for (i = 0; i < bars ; i++) 
			{
				current = 0;
				for (x = 0; x < Math.floor(256/bars) ; x++) {
                    current = Math.max(current, spectrum.readFloat());
				}
				current = Math.min( current, 1 );
				
				vOffset = (vInterval * current);
				g.drawRect( (i*span), vInterval + (vInterval - vOffset), span, vOffset );

			}
			g.endFill();
		}
	}
}